package com.myx.filter;

import com.myx.pojo.User;
import com.myx.tool.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = {"/jsp/admin/category/*",
        "/jsp/admin/comment",
        "/jsp/admin/common/*",
        "/jsp/admin/news/*",
        "/jsp/admin/user"})
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
        System.out.println("loginFilter init.....");
    }

    public void destroy() {
        System.out.println("loginFilter destory ...");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 进行是否登录的判断
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpSession session = httpServletRequest.getSession();
        User loginUser = (User) session.getAttribute(Constant.LOGIN_SESSION);
        if (loginUser == null) {
            // 未登录
            // System.out.println(" LoginFilter 检查到未登录。。。。");
            httpServletRequest.setAttribute("","");
            httpServletRequest.getRequestDispatcher("/index.jsp").forward(httpServletRequest,httpServletResponse);
        }else {
            // 有用户登录
            //  System.out.println(" LoginFilter 检查到已经登录放行通过。。。。");
        }

        chain.doFilter(request, response);
    }
}
